<template>
  <div class="base-page">
    <div class="left">
      <contract-manage @select="contractManageHandel" />
    </div>
    <!-- 列表 -->
    <div class="right" v-show="viewList === true">
      <div class="e-table">
        <div class="top">
          <div class="left">
            <div class="left-btn">
              <el-button type="primary"
                         @click="onDistRole"
                         class="btn-greenYellow"
              >新增</el-button>
            </div>
          </div>
          <div class="search_box">
            <el-input class="ipt" type="text"
                      placeholder="输入机构名称"
                      v-model="searchKey"
                      @select="onSearch"
                      @change="onSearch"
            ><img src="@/assets/search.png" slot="suffix" @click="onSearch" /></el-input>
            <!-- <div class="adverse">
              <el-button type="primary" @click="onAdvanceSearch">高级搜索</el-button>
            </div> -->
          </div>
        </div>
      </div>
      <div class="e-table" :style="{width: rightTableWidth}">
        <el-table
            class="table"
            :height="rightTableHeight"
            :data="tableData"
            border
            :cell-class-name="cellClsNm"
            highlight-current-row
            @current-change="handleCurrentChange"
            ref="tableRef"
            v-sortTable="{ 'tableData': tableData, '_this': this, 'ref': 'tableRef' }"
        >
          <el-table-column label="序号" type="index" width="55"> </el-table-column> <el-table-column label="操作" fixed width="250px" align="left"  sortable>
          <template slot-scope="{ row }">
            <div class="oparation_box">
              <i
                  class="el-icon-edit"
                  style="font-size: 24px"
                  title="编辑"
                  @click="edit(row)"
              ></i>
              <i
                  class="el-icon-delete"
                  style="font-size: 24px"
                  title="删除"
                  @click="deleteEle(row)"
              ></i>
            </div>
          </template>
        </el-table-column>
          <el-table-column prop="orgName" label="机构名称" min-width="300"> </el-table-column>
          <el-table-column prop="quota" label="合同限额（元）" min-width="200" show-overflow-tooltip> </el-table-column>
        </el-table>
      </div>
      <Pagination
          :total="paginationInfo.total"
          :pageSize.sync="paginationInfo.limit"
          :currentPage.sync="paginationInfo.page"
          @currentChange="getTableData"
          @sizeChange="getTableData"
      />
    </div>
    <!-- 填写合同限额信息页面 -->
    <div class="right" v-if="viewList === 'add'|| viewList === 'edit'">
      <div class="e-form" style="padding: 0 10px 10px;">
        <div class="tabs-title">合同限额配置信息</div>
        <el-form ref="form" :model="formData" label-width="160px" :rules="rules">
          <el-row>
            <el-col :span='12'>
              <el-form-item label="机构名称" prop='orgName'>
                <el-input placeholder="请输入机构名称" v-model="formData.orgName" readonly="" class="input-with-select">
                  <el-button slot="append" icon="el-icon-thumb" @click='onSelectOrg'></el-button>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span='12'>
              <el-form-item label="合同限额（元）" prop='quota'>
                <el-input placeholder="请输入合同限额（元）" v-model="formData.quota" class="input-with-select">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <!-- </el-table> -->
        </el-form>
      </div>
      <div class="footer">
        <div class="right-btn">
          <el-button type="primary"
                     @click="onSave"
          >保存</el-button>
          <el-button
              @click="onCancel"
          >取消</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import { mapMutations, mapState } from 'vuex'
import contractManage from '@/components/contractManage'
import Pagination from '@/components/pagination/pagination'
// eslint-disable-next-line no-unused-vars
// import { getUserUnderOrgApi, saveOrgRoleApi, getRoleByOrg } from '@/api/base/system'
import { saveBasicSettingsData, getBasicSettingsData, deleteBasicSettingsData, updateBasicSettingsData } from '@/api/base/contract'
// eslint-disable-next-line no-unused-vars
import { debounce, advanceSearch, selectDataClient, openAppClient } from '@/utils/common'
export default {
    name: 'contractLimitSetting',   //合同限额配置
    components: {
        Pagination,
        contractManage
    },
    computed: {
        ...mapState(['userInfo']),
        // 列表宽度
        rightTableWidth () {
            return (this.screenWidth - 300) + 'px'
        },
        // 列表高度
        rightTableHeight () {
            if (this.paginationInfo.total > 0) {
                return this.screenHeight - 170
            } else {
                return this.screenHeight - 118
            }
        },
        // 分配用户、分配岗位列表宽度
        rightTableWidth2 () {
            return (this.screenWidth - 300) + 'px'
        },
        rightTableHeight2 () {
            return this.screenHeight - 210
        }
    },
    watch: {
    },
    data () {
        return {
            rules: {
                orgName: [
                    { required: true, message: '请填写机构名称', trigger: 'blur' },
                ],
                quota: [
                    { required: true, message: '请填写合同限额金额', trigger: 'blur' },
                ],
            },
            formData: {
                'billId': '',
                'contractCategoryId': '',
                'orgId': '',
                'orgName': '',
                'quota': 0
            },
            billIds: [],
            searchKey: '',
            viewList: true, // 显示列表还是编辑界面: true 显示列表 false 显示编辑界面
            treeData: [],
            currentRow: null,
            paginationInfo: {
                'contractCategoryId': '',
                'key': '',
                'limit': 10,
                'page': 1
            },
            tableData: [],
            allData: [],
            currencyOptions: [],
            tabsName: 'baseInfo',
            tableData2: [],
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            idsTop: [],
            getformData: {}    //点击获取的数据
        }
    },
    mounted () {
        this.formData.orgName = this.userInfo.orgInfo.orgName
        this.formData.orgId = this.userInfo.orgInfo.orgId
        // 获取屏幕宽高
        this.getScreenInfo()
        window.addEventListener('resize', debounce(this.getScreenInfo))
    },
    methods: {
        ...mapMutations(['setSelectedInfo']),
        edit (row) {
            this.viewList = 'edit'
            this.formData = row
        },
        deleteEle (row) {
            this.billIds.push(row.billId)
            this.clientPop('info', '确定要删除吗？数据删除后不可恢复，请谨慎操作', ()=>{
                deleteBasicSettingsData(this.billIds).then(()=>{
                    this.clientPop('suc', '删除成功', ()=>{
                        this.getTableData()
                    })
                })
            })
        },
        //获取机构数据
        onSelectOrg () {
            // const val = [{ 'orgId': '1439990097591140354', 'orgName': '四川路桥建设集团股份有限公司', 'shortCode': 'SRBC', 'orgType': '1', 'parentId': '0', 'parentName': '' }]
            // this.formData.orgId = val[0].orgId
            // this.formData.orgName = val[0].orgName
            // this.formData.name = val[0].parentName   //差一个字段  差扣回款编码字段
            selectDataClient({
                SelectServiceToken: '/hr/org/getChildrenOrg', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: [], // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[])
                InitParamsStr: '',    // 接口参数(name为模拟参数)
                Title: '选择机构' // 标题
            }).then(val => {
                this.formData.orgId = val[0].orgId
                this.formData.orgName = val[0].orgName
                this.formData.name = val[0].parentName   //差一个字段  差扣回款编码字段
            })
        },
        async getTableData () {
            let marginData = await getBasicSettingsData(this.paginationInfo)
            console.log(marginData)
            this.tableData = marginData.list
            this.paginationInfo.total = marginData.totalCount
        },
        async queryTableData () {
            const resData = this.tableData.filter(item => {
                console.log(item)
                console.log(this.searchKey)
                return item.orgName.includes(this.searchKey)
            })
            this.tableData = resData
            this.paginationInfo.total = 0
        },
        contractManageHandel (val) {
            this.viewList = true
            this.getformData = {
                ...val
            }
            this.formData.contractCategoryId = this.getformData.billId
            this.formData.isLower = this.getformData.parentId === '0' && this.getformData.children.length > 0 ? true : false //是否是父级
            this.paginationInfo.contractCategoryId = this.getformData.billId
            this.getTableData()
        },
        cellClsNm ({ column }) {
            if (column.label === '') {
                return 'fixed-left'
            }
        },
        onSearch (e) {
            if(e === '') {
                this.getTableData()
            }else{
                let searchKey = e
                if (typeof e === 'object') {
                    searchKey = this.searchKey
                }
                this.paginationInfo.key = searchKey
                this.getTableData()
            }
        },
        onAdvanceSearch () {
            advanceSearch().then(res => {
                alert(JSON.stringify(res))
            })
        },
        handleCurrentChange (val) {
            this.currentRow = val
        },
        // 新增保证金数据
        onDistRole () {
            this.formData.orgName = this.userInfo.orgInfo.orgName
            this.formData.orgId = this.userInfo.orgInfo.orgId
            if(!this.formData.contractCategoryId) {
                this.clientPop('err', '请选择合同类别')
            }else if(this.formData.isLower) {
                this.clientPop('err', '只能在最子级类别新增')
            }else{
                this.viewList = 'add'
                // this.formData = {}
                this.formData.quota = 0
            }
        },
        // 保存新增或修改保证金数据
        async onSave () {
            this.$refs['form'].validate(async valid => {
                if (valid) {
                    if(this.viewList === 'add') {
                        saveBasicSettingsData(this.formData).then(()=>{
                            this.clientPop('suc', '保存成功', () => {
                                this.viewList = true
                            })
                            this.getTableData()
                        })
                        this.formData = {
                            'billId': '',
                            'contractCategoryId': this.getformData.billId,
                            'orgId': '',
                            'orgName': '',
                            'quota': 0
                        }
                    }else if(this.viewList === 'edit') {
                        updateBasicSettingsData(this.formData).then(() =>{
                            this.clientPop('suc', '保存成功', () => {
                                this.viewList = true
                            })
                            this.getTableData()

                        })

                    }
                }
            })
        },
        onCancel () {
            this.formData.orgName = this.userInfo.orgInfo.orgName
            this.formData.orgId = this.userInfo.orgInfo.orgId
            this.viewList = true
            this.formData = {
                'billId': '',
                'contractCategoryId': this.getformData.billId,
                'orgId': '',
                'orgName': '',
                'quota': 0
            }
        },
        getScreenInfo () {
            let screenWidth = document.documentElement.clientWidth || document.body.clientWidth
            let screenHeight = document.documentElement.clientHeight || document.body.clientHeight
            this.screenWidth = screenWidth
            this.screenHeight = screenHeight
        },
    }
}
</script>

<style lang="scss" scoped>
</style>
